﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

namespace GameFramework.net
{
    public class Client
    {
        public Socket socket;
        public String name;
        private Thread receiveSocket;
        public int move = 0;//-1左 0 停止 1右
        public int index = 0;// 1 2 
        public Vector3 basePos;
        public GameObject obj;
        public Client(Socket clientSocket,String name)
        {
            this.socket = clientSocket;
            this.name = name;

        }

        public void receiveMsg()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024*24];
                    //实际接收到的有效字节数
                    int len = socket.Receive(buffer);
                    string msg = Encoding.UTF8.GetString(buffer);
                    Debug.Log(DateTime.Now+"收到客户端 "+name+" 的数据 ： " + msg);
                    if (len == 0)
                    {
                        break;
                    }
                    //服务端处理
                    
                    //直接转发
                    NetManager.Instance.broadCastMsg(msg);

                }
                catch { }
            }
        }

        public void start()
        {
            if(receiveSocket!=null){
                return;
            }
            receiveSocket = new Thread(receiveMsg);
            receiveSocket.IsBackground = true;
            receiveSocket.Start();
        }

        public void close()
        {
            if (receiveSocket != null)
            {
                receiveSocket.Abort();
            }
        }

        public void send(string msg)
        {
            socket.Send(Encoding.UTF8.GetBytes(msg));
        }
    }
}